<template>
  <div class="page">
    <div v-if="isPay != true" class="pay">
      <label class="overdue"
        >您的插件已过期，请选择下面的套餐重新购买使用！</label
      >
      <button @click="payMent('codeAutoYear')">购买1年</button>
      <button @click="payMent('codeAutoMonth')">购买1月</button>
      <button @click="payMent('codeAutoDay')">购买1天</button>
    </div>
    <div v-else>
      <el-container class="page_container">
        <el-header class="window_title" style="height: 40px">
          <div>码农专用sql工具</div>
          <div>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-minus"
              @click="min_window"
            ></el-button>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-copy-document"
              @click="max_window"
            ></el-button>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-close"
              @click="close_window"
            ></el-button>
          </div>
        </el-header>
        <el-header class="main_title" style="">
          <el-button type="primary" icon="el-icon-circle-plus" @click="addConn">
            添加连接
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-sort"
            @click="structureContrast"
            >结构对比</el-button
          >
        </el-header>
        <el-container>
          <el-aside
            ref="pageElAside"
            class="page-el-aside"
            :width="elAsideTreeWidth + 'px'"
          >
            <el-input
              v-model="filterText"
              placeholder="输入筛选内容即可筛选"
            ></el-input>
            <div class="treeDiv">
              <el-tree
                ref="space"
                :data="data"
                node-key="id"
                :highlight-current="true"
                default-expand-all
                :expand-on-click-node="false"
                :check-on-click-node="true"
                @current-change="contextMenuChange"
                @node-contextmenu="nodeContextmenu"
                :filter-node-method="filterNode"
              >
                <span slot-scope="{ node, data }" class="custom-tree-node">
                  <span class="custom-tree-node-span">
                    <img
                      src="@/assets/images/mysql_logo.png"
                      v-if="data.dbType == 'mysql'"
                      alt=""
                    />
                    <img
                      src="@/assets/images/mssql_logo.png"
                      v-if="data.dbType == 'mssql'"
                      alt=""
                    />
                    <img
                      src="@/assets/images/sqlite_logo.png"
                      v-if="data.dbType == 'sqlite'"
                      alt=""
                    />
                    <img
                      src="@/assets/images/redis_logo.png"
                      v-if="data.dbType == 'redis'"
                      alt=""
                    />
                    <el-icon v-if="data.dbType == 'dbTable'"><coin /></el-icon>
                    {{ node.label }}
                  </span>
                </span>
              </el-tree>
            </div>

            <div class="right-move" @mousedown="move"></div>
          </el-aside>
          <el-container>
            <el-main>
              <el-tabs
                v-model="editableTabsValue"
                type="card"
                @edit="handleTabsEdit"
              >
                <el-tab-pane
                  v-for="(item, index) in editableTabs"
                  :key="item.title"
                  :label="item.title"
                  :name="item.name"
                  :closable="item.closable"
                >
                  <tabPanel
                    @change_content="change_content"
                    v-on:opentable="openTable"
                    v-on:editStructure="editStructure"
                    v-on:reConn="reConn"
                    :key="item.name"
                    :content="item.content"
                    :connId="item.connId"
                    :isconnect="item.isconnect"
                  />
                </el-tab-pane>
              </el-tabs>
            </el-main>
            <!-- <el-footer>Footer</el-footer> -->
          </el-container>
        </el-container>
      </el-container>

      <!-- 连接右键菜单 -->
      <vue-context-menu
        :context-menu-data="connMenu"
        @editConn="editConn"
        @refreshConn="refreshConn"
        @openTable="openTable"
      ></vue-context-menu>
      <!-- 数据库右键菜单 -->
      <vue-context-menu
        :context-menu-data="dataBaseMenu"
        @openTable="openTable"
        @performSql="performSql"
        @refreshData="refreshData"
        @createTable="createTable"
      ></vue-context-menu>
      <!-- 数据表右键菜单 -->
      <vue-context-menu
        :context-menu-data="dataTableMenu"
        @openTable="openTable"
        @editStructure="editStructure"
        @deletetable="deletetable"
      ></vue-context-menu>

      <!-- 连接窗口 -->
      <el-dialog
        title="链接地址"
        :visible.sync="connFormVisible"
        :close-on-click-modal="false"
      >
        <addConn
          :key="checkMenuItemId + connFormVisible"
          :check-menu-item-id="checkMenuItemId"
          :conn-form-visible="connFormVisible"
          @closeAddConn="closeAddConn"
        />
      </el-dialog>

      <!-- 结构对比窗口 -->
      <el-dialog
        title="结构对比"
        :visible.sync="diffStructureFormVisible"
        :close-on-click-modal="false"
        width="80%"
      >
        <diffStructure
          :key="diffStructureFormVisible"
          @closeStructureContrast="closeStructureContrast"
        />
      </el-dialog>

      <!-- <generator /> -->
    </div>
  </div>
</template>
<style lang="stylus">
#app {
  overflow: hidden;
}

.page_container {
  height: 100%;

  &>.el-header.window_title {
    line-height: 40px;
    position: relative;
    z-index: 10000;
    background: #3c3c3c;
    display: flex;
    justify-content: space-between;
    -webkit-app-region: drag;
    cursor: move;

    & button {
      -webkit-app-region: no-drag;
    }

    &>div {
      color: #fff;
    }
  }

  &>.el-header.main_title {
    line-height: 60px;
    background: #6c6c6c;
    -webkit-app-region: no-drag;

    & * {
      -webkit-app-region: no-drag;
    }
  }

  .page-el-aside {
    background: #ddd;
    // display: flex;
    overflow-y: hidden;
    position: relative;

    &>div.treeDiv {
      flex: 100;
      height: calc(100% - 40px);
      overflow-y: auto;

      &>.el-tree {
        overflow-x: hidden;

        .custom-tree-node {
          .custom-tree-node-span {
            display: flex;
            align-items: center;
            line-height: 20px;

            img {
              width: 20px;
              height: 20px;
            }
          }
        }
      }
    }

    &>.right-move {
      width: 3px;
      background: #666;
      cursor: e-resize;
      height: 100%;
      position: absolute;
      right: 0;
      top: 0;
    }
  }

  & .el-main {
    overflow: hidden;
  }
}
</style>
<script>
// var mysql = require("mysql"); //引入mysql模块
// var mysql =this.$mysql; //引入mysql模块
import generator from "../../components/generator.vue";

import addConn from "./components/addConn";
import tabPanel from "./components/tab_panel/index";

import diffStructure from "./components/diffStructure/index";

import { appStore } from "vuex";

let mysql;

// 定义商品id
const goods = {
  codeAutoDay: "72TIrlcYssdYs3SulXX6CsmrUmHpAnk3",
  codeAutoMonth: "c7IK84iY4SIq4H6BWXzauZiaNBGqvXWF",
  codeAutoYear: "ZIk8dDRXgzgSMs3TX2rSy1QLeS4SDXnh",
};

export default {
  name: "App",
  components: { generator, addConn, tabPanel, diffStructure },
  data() {
    return {
      isPay: true,
      connFormVisible: false,

      editableTabsValue: "1",

      diffStructureFormVisible: false,

      //空间树数据
      spaceTreeData: [],
      //默认树结构的输出格式
      defaultProps: {
        children: "children",
        label: "name",
      },
      filterText: "",

      checkMenuItemId: 0,
      connStting: {},
      dbStting: {},
      elAsideTreeWidth: 300,
      treeClickCount: 0,
      editableTabs: [
        {
          title: "对象",
          name: "1",
          closable: false,
          content: {
            tabType: "object",
            data: [],
          },
        },
        // {
        //     title: "Tab 2",
        //     closable: true,
        //     name: "2",
        //     content: {
        //         tabType: "table",
        //         data: {},
        //     },
        // },
      ],
      tabIndex: 2,

      data: [
        {
          id: "1",
          label: "请先添加数据库链接",
          type: "connection",
          dbUserName: "adafd",
          dbDatabaseName: "adafd",
          dbPassword: "adafd",
          dbPort: "adafd",
          dbConnected: false,
          dbType: "mysql",
        },

        // {
        //     id: "1",
        //     label: "myhost",
        //     type: "connection",
        //     dbUserName: "adafd",
        //     dbDatabaseName: "adafd",
        //     dbPassword: "adafd",
        //     dbPort: "adafd",
        //     dbConnected: false,
        //     dbType: "mysql",
        //     children: [
        //         {
        //             type: "dataBase",
        //             label: "数据库 1-1",
        //             children: [
        //                 {
        //                     label: "表 1-1",
        //                     type: "dbTable",
        //                 },
        //                 {
        //                     label: "表 1-2",
        //                     type: "dbTable",
        //                 },
        //             ],
        //         },
        //     ],
        // },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },

      // 连接右键菜单
      connMenu: {
        // 菜单显示的位置
        axis: {
          x: null,
          y: null,
        },
        // 连接右键
        menulists: [
          {
            fnHandler: "editConn", // 绑定事件
            icoName: "fa fa-home fa-fw", // icon图标
            btnName: "修改连接", // 菜单名称
          },
          {
            fnHandler: "refreshConn",
            icoName: "fa fa-minus-square-o  fa-fw",
            btnName: "刷新",
          },
          {
            fnHandler: "deleteConn",
            icoName: "fa fa-minus-square-o  fa-fw",
            btnName: "删除",
          },
        ],
      },

      // 数据库右键菜单
      dataBaseMenu: {
        menuName: "dataBaseMenu",
        // 菜单显示的位置
        axis: {
          x: null,
          y: null,
        },
        // 菜单选项
        menulists: [
          {
            fnHandler: "home", // 绑定事件
            icoName: "fa fa-home fa-fw", // icon图标
            btnName: "修改数据库", // 菜单名称
          },
          {
            fnHandler: "createTable", // 绑定事件
            icoName: "fa fa-home fa-fw", // icon图标
            btnName: "创建数据表（Alt+N）", // 菜单名称
          },

          {
            fnHandler: "performSql",
            icoName: "fa fa-minus-square-o  fa-fw",
            btnName: "执行SQL（Alt+Q）",
          },
          {
            fnHandler: "refreshData",
            icoName: "fa fa-minus-square-o  fa-fw",
            btnName: "刷新 (Alt+F5)",
          },
        ],
      },
      // 数据表右键菜单
      dataTableMenu: {
        menuName: "dataTableMenu",
        // 菜单显示的位置
        axis: {
          x: null,
          y: null,
        },
        // 菜单选项
        menulists: [
          {
            fnHandler: "openTable", // 绑定事件
            icoName: "fa fa-home fa-fw", // icon图标
            btnName: "打开表（Alt+O）", // 菜单名称
          },
          {
            fnHandler: "editStructure",
            icoName: "fa fa-minus-square-o  fa-fw",
            btnName: "设计表（Alt+D）",
          },

          {
            fnHandler: "deletedata",
            icoName: "fa fa-minus-square-o  fa-fw",
            btnName: "刷新（Alt+R）",
          },
          {
            fnHandler: "deletetable",
            icoName: "fa fa-minus-square-o  fa-fw",
            btnName: "删除（Alt+D）",
          },
        ],
      },
    };
  },
  //监听搜索框的查询参数变化，然后进行过滤
  watch: {
    filterText(val) {
      this.$refs.space.filter(val);
    },
  },
  mounted() {
    // 请求数据，赋值数据 等等一系列操作...
    // 监听窗口发生变化，resize组件
    window.addEventListener("setItem", () => {
      this.newVal = sessionStorage.getItem("watchStorage");
      var data = JSON.parse(this.newVal);
      console.log(data);
    });
  },
  async created() {
    this.watchKeyEvent();
    mysql = this.$mysql;
    this.initDbs();
    console.log(this.data);

    this.$uilt.ipcRenderer.on("ping", (event, data) => {
      console.log(event);
      console.log(data);

      this.senderId = event.senderId;
      let res_data = {};
      res_data.status = 1;
      res_data.message = "收到初始";
      this.$uilt.ipcRenderer.sendTo(this.senderId, "initResult", res_data);
    });

    // this.$utools.openPayment({ goodsId: 'yTGN12dg5nKhY6FlAAzkUKxPuAVzLeHh' }, () => {
    //   console.log('支付完成')
    // })

    //    获取用户所有购买的
    // await this.$utools.onPluginReady(async () => {

    await this.$uilt.onPluginReady().then(async () => {
      console.log("插件装配完成，已准备好");

      // 由于程序是新窗口用户进入插件已无法使用
      //   utools.db.put({
      //     _id: "sql_dbs",
      //     data: this.dbs,
      //   });

      await this.$utools.onPluginEnter(async ({ code, type, payload }) => {
        console.log("用户进入插件", code, type, payload);
        let isPay = await this.havePay();
        console.log(isPay);
        if (isPay == true) {
          this.isPay = true;
        } else {
          this.isPay = false;
        }
      });
    });

    let code = 0;
    let code2 = 0;
    document.onkeydown = (e) => {
      // let key = window.event.keyCode;
      // if (key == 13) {
      //   this.submit();
      // }
      if (e.key == "o" && e.altKey == true) {
        console.log("Alt+O");
        this.openTable();
      }
      // let evn = e || window.event;
      // let key = evn.keyCode || evn.which || evn.charCode;
      // if (key!==code && code!=0) {
      //   code2 = key;
      // }else{
      //   code=key;
      // }
      // console.log(code,code2)
      // if ((code === 18 && code2 === 79 )  ||(code2 === 18 && code === 79 ) ) {
      //   console.log("Alt+O");
      //   //do something
      //   code = 0;
      //   code2 = 0;
      // }

      //  if (code === 18 && code2 === 79) {
      //   console.log("Alt+D");
      //   //do something
      //   code = 0;
      //   code2 = 0;
      // }
    };

    // await this.$utools.openPayment({ goodsId: goods.codeAuto }, () => {
    //   // 用户完成支付，继续业务代码
    // });
  },
  // async beforeMount () {
  //   //    获取用户所有购买的
  //   await this.$utools.onPluginReady(async () => {
  //     console.log('插件装配完成，已准备好')

  //     await this.$utools.onPluginEnter(async ({ code, type, payload }) => {
  //       console.log('用户进入插件', code, type, payload)
  //       var isPay = await this.havePay()
  //       console.log(isPay)
  //       if (isPay == true) {
  //         this.isPay = true
  //       } else {
  //         this.isPay = false
  //       }
  //     })
  //   })
  //   await this.$utools.onPluginOut(() => {
  //     console.log('用户退出插件')
  //   })
  //   // await this.$utools.openPayment({ goodsId: goods.codeAuto }, () => {
  //   //   // 用户完成支付，继续业务代码
  //   // });
  // },
  methods: {
    closeStructureContrast() {
      this.diffStructureFormVisible = false;
    },
    structureContrast() {
      this.diffStructureFormVisible = true;
    },
    change_content(new_tab) {
      this.data[new_tab.data.connIndex].children[new_tab.data.dbIndex].children[
        new_tab.data.tableIndex
      ].label = new_tab.data.tableTitle;

      this.editableTabs.forEach((item, i) => {
        if (item.content.data.tableIndex == new_tab.data.tableIndex) {
          item.content.data.tableTitle = new_tab.data.tableTitle;

          if (item.content.tabType == "structure") {
            item.title = `${item.content.data.tableTitle}@${item.content.data.dbITitle}(${item.content.data.connTitle})`;
          }

          if (item.content.tabType == "table") {
            item.title = `${new_tab.data.tableTitle}@${item.content.data.dbITitle}(${item.content.data.connTitle})`;
          }
        }
      });

      console.log(this.editableTabs);
    },

    //优化之后的代码 不管有几级都可以适用,不过用了递归，量太大还是会崩溃，这个后续需要优化
    filterNode(value, data, node) {
      if (!value) return true;
      return this.findSearKey(node, value);
    },
    //递归搜索父级是否包含关键字
    findSearKey(node, key) {
      if (node.label.indexOf(key) !== -1) {
        return true;
      } else {
        if (node.parent.parent == null) {
          return false;
        } else {
          return this.findSearKey(node.parent, key);
        }
      }
    },
    // 对比两个dom的ref是否相同
    searchDomRefParent(dom, parent_ref) {
      // console.log(dom.parentNode);debugger
      console.log(dom.parentNode.getAttribute("class"));
      if (dom.getAttribute("class") == null && dom.parentNode !== null) {
        return true;
      }

      // dom.parentNode
    },
    watchKeyEvent() {
      let that = this;
      const setKeyStatus = (keyCode, status) => {
        switch (keyCode) {
          case "16":
            if (this.onShfit === status) return;
            console.log("shif", status ? "按下" : "抬起");
            this.onShfit = status;
            break;
          case "Control":
            if (this.onCtrl === status) return;
            console.log("ctrl", status ? "按下" : "抬起");
            this.onCtrl = status;
            break;
        }
      };
      document.onkeydown = (e) => {
        var x = document.activeElement;
        console.log(x, 1);

        setKeyStatus(e.key, true);
      };
      document.onkeyup = (e) => {
        var x = document.activeElement;
        console.log(that.searchDomRefParent(x, "pageElAside"));
        //                if( that.searchDomRefParent(x,'pageElAside')){
        // // 如果光标在左侧

        //                }
        //                 console.log(x, 1);
        // console.log(x.parentNode)
        setKeyStatus(e.key, false);
      };
    },
    min_window() {
      this.$uilt.ipcRenderer.sendTo(this.senderId, "minimizeSqlWindow");
    },
    max_window() {
      this.$uilt.ipcRenderer.sendTo(this.senderId, "maximizeSqlWindow");
    },
    close_window() {
      this.$uilt.ipcRenderer.sendTo(this.senderId, "closeSqlWindow");
    },

    move(e) {
      // elAsideTree
      // let elAsideTree=this.$refs.elAsideTree;
      let odiv = e.target; // 获取目标元素
      // 算出鼠标相对元素的位置
      let disX = e.clientX - odiv.offsetLeft;
      let disY = e.clientY - odiv.offsetTop;
      document.onmousemove = (e) => {
        // 鼠标按下并移动的事件
        // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX;

        this.elAsideTreeWidth = left;
      };
      document.onmouseup = (e) => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    },

    initDbs() {
      let dbs = this.$utools.db.get("connObject") || false;
      if (dbs != false) {
        this.data = dbs.data;
        // if (this.checkMenuItemId != 0) {
        //   this.data.forEach((db_item, db_i) => {
        //     if (db_item.id == this.checkMenuItemId) {
        //       db_item.conn = mysql.createConnection({
        //         // 创建mysql实例
        //         port: "3306",
        //         host: "localhost",
        //         user: "r666t",
        //         password: "shi666",
        //         // database: "test666",
        //       });
        //     }
        //   });
        // }
      }
    },
    addConn() {
      this.connFormVisible = true;
      this.checkMenuItemId = 0;
    },
    closeAddConn() {
      this.connFormVisible = false;
      this.initDbs();
    },

    reConn(connId) {
      this.checkMenuItemId = connId;
      console.log(this.checkMenuItemId);
      this.refreshConn();
    },
    refreshConn() {
      let that = this;
      let thatData = that.data;
      if (this.checkMenuItemId == 0) {
        that.$message.error("操作失败");
        return;
      }
      thatData.forEach((connItime, conIndex) => {
        if (connItime.id == this.checkMenuItemId) {
          that.treeClickCount = 1;
          let data = connItime;
          data.type = "connection";
          that.contextMenuChange(data);
        }
      });
    },

    // 刷新数据库表内容
    refreshData() {
      let that = this;
      let thatData = that.data;
      if (this.checkMenuItemId == 0) {
        that.$message.error("操作失败");
        return;
      }
      console.log(that.checkMenuItemId);

      console.log(111);
      thatData.forEach((connItime, conIndex) => {
        console.log(
          connItime.hasOwnProperty("children") && connItime.children != null
        );
        if (
          connItime.hasOwnProperty("children") &&
          connItime.children != null
        ) {
          connItime.children.forEach((dbItime, dIndex) => {
            if (dbItime.id == this.checkMenuItemId) {
              that.treeClickCount = 1;
              let data = dbItime;
              data.type = "dataBase";
              that.contextMenuChange(data);
            }
          });
        }
      });
      thatData.forEach((connItime, conIndex) => {});
    },
    handleTabsEdit(targetName, action) {
      if (action === "add") {
        let newTabName = ++this.tabIndex + "";
        this.editableTabs.push({
          title: "New Tab",
          name: newTabName,
          content: "New Tab content",
        });
        this.editableTabsValue = newTabName;
      }
      if (action === "remove") {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
            }
          });
        }

        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter((tab) => tab.name !== targetName);
      }
    },
    contextMenuChange(data) {
      let that = this;
      let thatData = that.data;
      let connIndex = 0;
      let dbIndex = 0;
      let tableIndex = 0;

      let connTitle = "";
      let dbITitle = "";
      let tableTitle = "";

      that.treeClickCount++;
      if (this.treeClickCount > 2) return;
      setTimeout(() => {
        if (that.treeClickCount == 1) {
          // 进行单击事件处理
          console.log("单击事件", data);

          if (data.type == "dbTable") {
            this.data.forEach((conn_item, conn_i) => {
              if (conn_item.hasOwnProperty("children")) {
                conn_item.children.forEach((dbItem, dbI) => {
                  if (dbItem.hasOwnProperty("children")) {
                    dbItem.children.forEach((tbItem, tbI) => {
                      if (tbItem.id == data.id) {
                        this.connStting.index = conn_i;
                        this.connStting.id = conn_item.id;

                        this.connStting.dbIndex = dbI;
                        this.connStting.dbId = dbItem.id;

                        this.connStting.tbIndex = tbI;
                        this.connStting.tbId = tbItem.id;
                        console.log(this.connStting);
                        console.log(tbItem.id == data.id);
                      }
                    });
                  }
                });
              }
            });
          }
        } else if (that.treeClickCount == 2) {
          // 进行双击事件处理
          console.log("双击事件", data);

          thatData.forEach((connItime, conIndex) => {
            console.log(
              connItime.hasOwnProperty("children") && connItime.children != null
            );
            if (data.id == connItime.id) {
              connIndex = conIndex;
              connTitle = connItime.label;
            } else if (
              connItime.hasOwnProperty("children") &&
              connItime.children != null
            ) {
              connItime.children.forEach((dbItime, dIndex) => {
                if (data.id == dbItime.id) {
                  connIndex = conIndex;
                  dbIndex = dIndex;
                  connTitle = connItime.label;
                  dbITitle = dbItime.label;
                } else if (
                  dbItime.hasOwnProperty("children") &&
                  dbItime.children.length != null
                ) {
                  dbItime.children.forEach((tItime, tIndex) => {
                    if (data.id == tItime.id) {
                      connIndex = conIndex;
                      dbIndex = dIndex;
                      tableIndex = tIndex;
                      connTitle = connItime.label;
                      dbITitle = dbItime.label;
                      tableTitle = tItime.label;
                    }
                  });
                }
              });
            }
          });

          this.connStting.index = connIndex;

          console.log(data.type);
          if (data.type == "connection") {
            if (
              !data.hasOwnProperty("conn") ||
              data.conn == null ||
              data.isconnect == false
            ) {
              that.connect(data).then(() => {
                // let dbData = data.conn;
                console.log(data);
                if (data.conn == null) {
                  return;
                }
                if (!data.hasOwnProperty("children") || data.children == null) {
                  this.sqlQuery("show databases", false).then(
                    (showDatabases) => {
                      console.log(showDatabases);

                      // 事先删除children   由于chidren 为null时 对他push元素会导致添加的元素 没有 __ob_:Observer ,页面也不渲染的问题
                      if (data.children == null) {
                        delete data.children;
                      }

                      that.$set(data, "children", []);
                      showDatabases.forEach((dbItems, dbI) => {
                        let dbObj = {
                          id: Math.round(Math.random() * 999999999),
                          type: "dataBase",
                          label: dbItems.Database,
                        };
                        data.children.push(dbObj);
                      });

                      console.log(data.children);

                      that.$forceUpdate();
                    }
                  );
                }
              });
            }
          }

          if (data.type == "dataBase") {
            let dbData = thatData[connIndex].conn;
            console.log(connIndex, dbData);
            // dbData.connect(function (err) {
            //   if (err) {
            //     console.error('数据库连接失败: ' + err.stack);
            //     that.$message.error(data.label + "接失败");
            //     return;
            //   }
            // if (!data.hasOwnProperty("children")) {
            dbData.query(
              "SELECT * FROM information_schema.`TABLES` WHERE 1 and `TABLE_SCHEMA` = '" +
                data.label +
                "' ORDER BY `TABLE_NAME` ASC",
              (error, results, fields) => {
                console.log(
                  "select table_name from information_schema.tables where table_schema='" +
                    data.label +
                    "' and table_type='base table'"
                );
                if (error) throw error;
                that.$set(data, "children", []);
                that.editableTabs[0].content.data = [];
                // data.children = [];
                results.forEach((dbItems, dbI) => {
                  console.log(1111);

                  let dbObj = {
                    id: Math.round(Math.random() * 999999999),
                    type: "dbTable",
                    label: dbItems.TABLE_NAME,
                  };
                  // console.log(that.editableTabs[0].content);debugger
                  that.editableTabs[0].content.data.push(dbItems);
                  that.editableTabsValue = "1";
                  data.children.push(dbObj);
                });

                that.$forceUpdate();
                console.log(results);
                console.log(that.data[connIndex]);
                // that.$set(that.data,dataIndex,data)

                // console.log('The solution is: ', results[0].solution);
              }
            );

            // dbData.end();
            // }
            // });
          }

          if (data.type == "dbTable") {
            //  connTitle = connItime.label;
            //                       dbITitle = dbItime.label;
            //                       tableTitle = tableTitle.label;
            // 表名@库名（连接名）
            // let newTabName = ++this.tabIndex + "";
            if (!that.data[connIndex].isconnect) {
              that.$message.error("与服务器断开连接,请重新连接后再打开表！");
              return;
            }
            let newTabName =
              connIndex + "_" + dbIndex + "_" + tableIndex + "_open_table";
            console.log(newTabName);
            if (!that.in_array(newTabName, this.editableTabs, "name")) {
              this.editableTabs.push({
                connId: that.data[connIndex].id,

                title: `${tableTitle}@${dbITitle}(${connTitle})`,
                name: newTabName,
                icon: "",
                closable: true,

                isconnect: that.data[connIndex].isconnect,
                content: {
                  tabType: "table",
                  data: {
                    connIndex,
                    dbIndex,
                    tableIndex,

                    connTitle,
                    dbITitle,
                    tableTitle,

                    conn: that.data[connIndex].conn,
                  },
                },
              });
            }
            this.editableTabsValue = newTabName;
          }
        }
        that.treeClickCount = 0;
      }, 500);
    },

    // 如果数据连接出错，则重新连接
    handleError(data) {
      let that = this;
      // logger.info(err.stack || err);
      // that.$message.error(err.stack || err);
      this.connect(data);
    },
    async connect(data) {
      let that = this;
      console.log(data, "开始连接");
      data.conn = mysql.createConnection({
        // 创建mysql实例
        port: data.dbPort,
        host: data.dbHost,
        user: data.dbUserName,
        password: data.dbPassword,
        // database: "test666",
        multipleStatements: true,
        useConnectionPooling: true,
      });
      let dbData = data.conn;
      await dbData.connect((err) => {
        if (err) {
          that.$message.error("与服务器断开连接2！", err);
          data.conn = null;
          this.editableTabs.forEach((item) => {
            if (item.connId == data.id) {
              console.log(11111111);
              data.isconnect = false;
              this.editableTabs.forEach((item) => {
                if (item.connId == data.id) {
                  console.log(333333);

                  item.content.data.conn = data.conn;
                  item.isconnect = data.isconnect;
                  // item.content.data.isconnect = true;
                }
              });
            }
          });
          // setTimeout(that.connect(data), 5000);
        }
      });
      dbData.on("error", (err) => {
        // console.log("db error", err);
        // 如果是连接断开，自动重新连接
        if (err.code === "PROTOCOL_CONNECTION_LOST") {
          that.$message.error("与服务器断开连接1！", err);
          data.isconnect = false;

          // handleError();
          // that.handleError(data);

          this.editableTabs.forEach((item) => {
            if (item.connId == data.id) {
              item.content.data.conn = data.conn;
              item.isconnect = data.isconnect;
              // item.content.data.isconnect = true;
              console.log(item);
            }
          });
        } else {
          throw err;
        }
      });
      data.isconnect = true;
      console.log(this.editableTabs);
      // dbData.on("error", that.handleError(data));
      if (data.isconnect == false) {
        console.log(111122222);
        return;
      }
      this.editableTabs.forEach((item) => {
        if (item.connId == data.id) {
          item.content.data.conn = data.conn;
          item.isconnect = data.isconnect;
          // item.content.data.isconnect = true;
        }
      });

      let pingInterval = "";
      // 每个小时ping一次数据库，保持数据库连接状态
      clearInterval(pingInterval);
      pingInterval = setInterval(() => {
        console.log("ping...");
        dbData.ping((err) => {
          if (err) {
            console.log("ping error: " + JSON.stringify(err));
          }
        });
      }, 3600000);
    },
    in_array(search, array, field = "") {
      if (field != "") {
        for (var i in array) {
          if (array[i][field] == search) {
            return true;
          }
        }
      } else {
        for (var i in array) {
          if (array[i] == search) {
            return true;
          }
        }
      }

      return false;
    },

    performSql() {
      let that = this;
      console.log("执行sql");
      let db_conns = this.data[this.connStting.index];
      let db_item_name = db_conns.children[this.connStting.dbIndex];
      console.log(db_item_name);
      let num_code = Math.round(Math.random() * 10000);
      let newTabName =
        this.connStting.index + "_" + this.connStting.dbIndex + "_" + num_code;

      this.editableTabs.push({
        connId: this.data[this.connStting.index].id,

        title: `${db_item_name.label}@${db_conns.label}(sql)【${num_code}】`,
        name: newTabName,
        icon: "",
        closable: true,

        isconnect: this.data[this.connStting.index].isconnect,

        content: {
          tabType: "sql",
          isconnect: this.data[this.connStting.index].isconnect,
          data: {
            dbIndex: this.connStting.dbIndex,

            dbITitle: db_item_name.label,
            conn: this.data[this.connStting.index].conn,
          },
        },
      });
      this.editableTabsValue = newTabName;
    },

    createTable() {
      console.log("创建表");

      // return;
      let that = this;

      console.log(this.connStting);
      let db_conns = this.data[this.connStting.index];
      let db_item_name = db_conns.children[this.connStting.dbIndex];

      let newTabName =
        this.connStting.index +
        "_" +
        Math.floor(Math.random() * 1000 + 1) +
        "_" +
        this.connStting.dbIndex +
        "_create_structure";
      if (!that.in_array(newTabName, this.editableTabs, "name")) {
        this.editableTabs.push({
          connId: db_conns.id,
          title: `${db_conns.label}@${db_item_name.label}(${db_conns.label})`,
          name: newTabName,
          icon: "",
          closable: true,
          isconnect: this.data[this.connStting.index].isconnect,

          content: {
            tabType: "structure",

            data: {
              dbIndex: this.connStting.dbIndex,
              connIndex: this.connStting.index,
              connTitle: db_conns.label,
              dbITitle: db_item_name.label,
              conn: this.data[this.connStting.index].conn,
            },
          },
        });
      }
      this.editableTabsValue = newTabName;
    },

    openTable(res = {}) {
      console.log(res.TABLE_NAME);
      if (res && res.TABLE_NAME) {
        this.data.forEach((d_v, d_i) => {
          if (d_v.hasOwnProperty("children")) {
            console.log(d_v.children);
            d_v.children.forEach((db_v, db_i) => {
              if (db_v.hasOwnProperty("children")) {
                db_v.children.forEach((tb, tb_i) => {
                  if (
                    tb.hasOwnProperty("label") &&
                    tb.label == res.TABLE_NAME
                  ) {
                    console.log(tb.label);
                    this.connStting.index = d_i;
                    this.connStting.dbIndex = db_i;
                    this.connStting.tbIndex = tb_i;
                  }
                });
              }
            });
          }
        });
      }

      console.log("打开表1");
      console.log(this.connStting);
      let that = this;
      let db_conns = this.data[this.connStting.index];
      let db_item_name = db_conns.children[this.connStting.dbIndex];
      let table_item =
        db_conns.children[this.connStting.dbIndex].children[
          this.connStting.tbIndex
        ];
      console.log(table_item);
      let num_code = Math.round(Math.random() * 10000);
      let newTabName =
        this.connStting.index +
        "_" +
        this.connStting.dbIndex +
        "_" +
        this.connStting.tbIndex +
        "_open_table";

      console.log(db_conns.isconnect);
      if (!db_conns.isconnect) {
        that.$message.error("与服务器断开连接,请重新连接后再打开表！");
        return;
      }

      if (!that.in_array(newTabName, this.editableTabs, "name")) {
        this.editableTabs.push({
          connId: table_item.id,
          title: `${table_item.label}@${db_item_name.label}(${db_conns.label})`,
          name: newTabName,
          icon: "",
          closable: true,
          isconnect: this.data[this.connStting.index].isconnect,

          content: {
            tabType: "table",

            data: {
              dbIndex: this.connStting.dbIndex,
              connIndex: this.connStting.index,
              tableIndex: this.connStting.tbIndex,
              connTitle: db_conns.label,
              tableTitle: table_item.label,
              dbITitle: db_item_name.label,
              conn: this.data[this.connStting.index].conn,
            },
          },
        });
      }

      this.editableTabsValue = newTabName;
    },
    sqlQuery(sql_text, return_status = true) {
      let that = this;
      return new Promise((resolve, reject) => {
        let db_conns = that.data[that.connStting.index];

        db_conns.conn.query(sql_text, (error, results, fields) => {
          if (error) {
            that.$message.error(error);
            // throw error;
            reject(error);
          }
          if (return_status) {
            results.status = 200;
          }
          resolve(results);
          // console.log(results[0].column_name);
          // column_name = results[0].column_name;
        });
      });
    },
    editStructure(res = {}) {
      console.log("设计表");
      // return;
      let that = this;

      console.log(res.TABLE_NAME);
      if (res && res.TABLE_NAME) {
        this.data.forEach((d_v, d_i) => {
          if (d_v.hasOwnProperty("children")) {
            console.log(d_v.children);
            d_v.children.forEach((db_v, db_i) => {
              if (db_v.hasOwnProperty("children")) {
                db_v.children.forEach((tb, tb_i) => {
                  if (
                    tb.hasOwnProperty("label") &&
                    tb.label == res.TABLE_NAME
                  ) {
                    console.log(tb.label);
                    this.connStting.index = d_i;
                    this.connStting.dbIndex = db_i;
                    this.connStting.tbIndex = tb_i;
                  }
                });
              }
            });
          }
        });
      }

      console.log(this.connStting);
      let db_conns = this.data[this.connStting.index];
      let db_item_name = db_conns.children[this.connStting.dbIndex];
      let table_item =
        db_conns.children[this.connStting.dbIndex].children[
          this.connStting.tbIndex
        ];
      console.log(table_item);
      let newTabName =
        this.connStting.index +
        "_" +
        this.connStting.dbIndex +
        "_" +
        this.connStting.tbIndex +
        "_edit_structure";
      if (!that.in_array(newTabName, this.editableTabs, "name")) {
        this.editableTabs.push({
          connId: table_item.id,
          title: `${table_item.label}@${db_item_name.label}(${db_conns.label})`,
          name: newTabName,
          icon: "",
          closable: true,
          isconnect: this.data[this.connStting.index].isconnect,

          content: {
            tabType: "structure",

            data: {
              dbIndex: this.connStting.dbIndex,
              connIndex: this.connStting.index,
              tableIndex: this.connStting.tbIndex,
              connTitle: db_conns.label,
              tableTitle: table_item.label,
              dbITitle: db_item_name.label,
              conn: this.data[this.connStting.index].conn,
            },
          },
        });
      }
      this.editableTabsValue = newTabName;
    },
    deletetable() {
      console.log("删除表");
      let that = this;

      console.log(this.connStting);
      let db_conns = this.data[this.connStting.index];
      let db_item_name = db_conns.children[this.connStting.dbIndex];
      let table_item =
        db_conns.children[this.connStting.dbIndex].children[
          this.connStting.tbIndex
        ];
      console.log(table_item);
      this.$confirm(`您确定要删除${table_item.label}数据表?`, "Warning", {
        confirmButtonText: "OK",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let use_datebase_sql = `USE \`${db_item_name.label}\`;`;
          let delete_table_sql = `drop table if exists  \`${table_item.label}\`;`;

          Promise.all([
            that.sqlQuery(use_datebase_sql),
            that.sqlQuery(delete_table_sql),
          ]).then((value) => {
            // console.log(db_item_name.label);
            // that.sqlQuery(use_datebase_sql).then(() => {
            //     that.sqlQuery(delete_table_sql).then(()=>{
            console.log(value);

            that.checkMenuItemId = db_item_name.id;

            that.refreshData();

            // 重新加载数据表
            that.$message({
              type: "success",
              message: "删除成功！",
            });
          });

          //     });

          // });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "您已取消删除！",
          });
        });
    },
    submit() {
      alert("监听到enter键");
    },
    nodeContextmenu(event, data) {
      console.log(event, data);
      let nowCoordinates = {};
      // 获取x 坐标
      nowCoordinates.x = event.clientX;
      // 获取y 坐标
      nowCoordinates.y = event.clientY;

      this.checkMenuItemId = data.id;

      if (data.type == "connection") {
        this.connMenu.axis = nowCoordinates;

        this.data.forEach((conn_item, conn_i) => {
          if (conn_item.id == this.checkMenuItemId) {
            this.connStting.index = conn_i;
            this.connStting.id = conn_item.id;

            this.connStting.dbIndex = -1;
            this.connStting.dbId = -1;

            this.connStting.tbIndex = -1;
            this.connStting.tbId = -1;
          }
        });
      }
      if (data.type == "dataBase") {
        this.dataBaseMenu.axis = nowCoordinates;

        this.data.forEach((conn_item, conn_i) => {
          if (conn_item.hasOwnProperty("children")) {
            conn_item.children.forEach((dbItem, dbI) => {
              if (dbItem.id == this.checkMenuItemId) {
                this.connStting.index = conn_i;
                this.connStting.id = conn_item.id;

                this.connStting.dbIndex = dbI;
                this.connStting.dbId = dbItem.id;

                this.connStting.tbIndex = -1;
                this.connStting.tbId = -1;
              }
            });
          }
        });
      }

      if (data.type == "dbTable") {
        this.dataTableMenu.axis = nowCoordinates;
        this.data.forEach((conn_item, conn_i) => {
          if (conn_item.hasOwnProperty("children")) {
            conn_item.children.forEach((dbItem, dbI) => {
              if (dbItem.hasOwnProperty("children")) {
                dbItem.children.forEach((tbItem, tbI) => {
                  if (tbItem.id == this.checkMenuItemId) {
                    this.connStting.index = conn_i;
                    this.connStting.id = conn_item.id;

                    this.connStting.dbIndex = dbI;
                    this.connStting.dbId = dbItem.id;

                    this.connStting.tbIndex = tbI;
                    this.connStting.tbId = tbItem.id;
                    console.log(this.connStting);
                  }
                });
              }
            });
          }
        });
      }
    },
    // 修改连接
    editConn() {
      this.connFormVisible = true;
    },
    async payMent(model) {
      await this.$utools.openPayment({ goodsId: goods[model] }, async () => {
        // 用户完成支付，继续业务代码
        let isPay = await this.havePay();
        if (isPay == true) {
          this.isPay = true;
        } else {
          this.isPay = false;
        }
      });
    },
    /* 获取上一个月
     *
     *  @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    getPreMonth(date) {
      date = this.DateToStr(date);
      let dateDay = date.split(" ");
      let arr = dateDay[0].split("-");
      let year = arr[0]; // 获取当前日期的年份
      let month = arr[1]; // 获取当前日期的月份
      let day = arr[2]; // 获取当前日期的日
      // var days = new Date(year, month, 0)
      // days = days.getDate() // 获取当前日期中月的天数
      let year2 = year;
      let month2 = parseInt(month) - 1;
      if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
      }
      let day2 = day;
      let days2 = new Date(year2, month2, 0);
      days2 = days2.getDate();
      if (day2 > days2) {
        day2 = days2;
      }
      if (month2 < 10) {
        month2 = "0" + month2;
      }
      let t2 = year2 + "-" + month2 + "-" + day2;
      if (dateDay[1]) {
        t2 = t2 + " " + dateDay[1];
      }
      return t2;
    },
    /* 获取上一年
     *
     *  @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    getPreYear(date) {
      date = this.DateToStr(date);

      let dateDay = date.split(" ");
      let arr = dateDay[0].split("-");
      let year = arr[0]; // 获取当前日期的年份
      let month = arr[1]; // 获取当前日期的月份
      let day = arr[2]; // 获取当前日期的日
      // var days = new Date(year, month, 0)
      // days = days.getDate() // 获取当前日期中月的天数
      let year2 = year;
      let month2 = parseInt(month);

      year2 = parseInt(year2) - 1;

      let day2 = day;
      let days2 = new Date(year2, month2, 0);
      days2 = days2.getDate();
      if (day2 > days2) {
        day2 = days2;
      }
      if (month2 < 10) {
        month2 = "0" + month2;
      }
      let t2 = year2 + "-" + month2 + "-" + day2;
      if (dateDay[1]) {
        t2 = t2 + " " + dateDay[1];
      }
      return t2;
    },
    // 比较两个时间的大小
    bjDate(date, date1) {
      date = new Date(date);
      date1 = new Date(date1);
      if (date.getTime() - date1.getTime() < 0) {
        return false;
      }
      return true;
    },
    // 日期转字符串格式
    DateToStr(date) {
      date = new Date(date);
      let year = date.getFullYear(); // 年

      let month = date.getMonth(); // 月
      let day = date.getDate(); // 日
      let hours = date.getHours(); // 时
      let min = date.getMinutes(); // 分
      let second = date.getSeconds(); // 秒
      return (
        year +
        "-" +
        (month + 1 > 9 ? month + 1 : "0" + (month + 1)) +
        "-" +
        (day > 9 ? day : "0" + day) +
        " " +
        (hours > 9 ? hours : "0" + hours) +
        ":" +
        (min > 9 ? min : "0" + min) +
        ":" +
        (second > 9 ? second : "0" + second)
      );
    },

    async havePay() {
      let that = this;
      await this.$utools.fetchUserPayments().then(async (ret) => {
        // 判断如果存在支付记录则继续相关业务
        // ret = [
        //   {
        //     order_id: 'ZsVSwEDoR7PPs6vWdAGplEpEpNjn8xb4', // utools 订单号
        //     out_order_id: '', // 外部订单号
        //     open_id: 'a331127d654761ac91d086b942aae7b6', // uTools 用户 ID, 对于此插件不变且唯一
        //     pay_fee: 1, // 支付金额（分）
        //     body: '会员1年', // 支付内容
        //     attach: '', // 附加数据
        //     goods_id: '6n193s7P95p9gA13786YkwQ5oxHpVW4f', // 商品 ID
        //     paid_at: '2021-06-18 16:55:26', // 支付时间
        //     created_at: '2021-06-18 16:55:11' // 订单生成时间
        //   },
        //   {
        //     order_id: 'ZsVSwEDoR7PPs6vWdAGplEpEpNjn8xb4', // utools 订单号
        //     out_order_id: '', // 外部订单号
        //     open_id: 'a331127d654761ac91d086b942aae7b6', // uTools 用户 ID, 对于此插件不变且唯一
        //     pay_fee: 1, // 支付金额（分）
        //     body: '会员1年', // 支付内容
        //     attach: '', // 附加数据
        //     goods_id: 'ef1ce46632c17e8fb8b305b1c715bd16', // 商品 ID
        //     paid_at: '2020-10-18 16:55:26', // 支付时间
        //     created_at: '2021-011-18 16:55:11' // 订单生成时间
        //   }
        // ]

        // var sdtime4 = new Date().setMonth(new Date().getMonth() - 1);
        // var sdtime4 = "2020-02-29 16:55:11";

        // var sdtime4 = new Date(sdtime4).setMonth(
        //   new Date(sdtime4).getMonth() - 1
        // );
        // console.log(new Date(sdtime4).getMonth());
        // console.log(sdtime4);

        // console.log(this.getPreMonth(sdtime4));
        // const goods = {
        //   codeAutoDay: "e9cfe6d15fad52b807eb5c8a3a0c4ba6",
        //   codeAutoMonth: "4694f055052d384fe07d1d4e4849542f",
        //   codeAutoYear: "ef1ce46632c17e8fb8b305b1c715bd16",
        // };
        // console.log(this.getPreYear(sdtime4));
        console.log(ret);
        that.isPay = false;
        ret.forEach((element, i) => {
          //    如果购买年套餐，时间差不大于1年，则通过
          //   console.log(
          //     goods.codeAutoYear == element.goods_id &&
          //       this.bjDate(element.paid_at, this.getPreYear(new Date()))
          //   );
          if (
            goods.codeAutoYear == element.goods_id &&
            this.bjDate(element.paid_at, this.getPreYear(new Date()))
          ) {
            that.isPay = true;
          }
          //    如果购买月套餐，时间差不大于1月，则通过
          if (
            goods.codeAutoMonth == element.goods_id &&
            this.bjDate(element.paid_at, this.getPreMonth(new Date()))
          ) {
            that.isPay = true;
          }

          //    如果购买日套餐，时间差不大于1天，则通过
          if (
            goods.codeAutoDay == element.goods_id &&
            this.bjDate(
              element.paid_at,
              new Date().setDate(new Date().getDate() - 1)
            )
          ) {
            that.isPay = true;
          }
        });
      });
      return that.isPay;
    },
  },
};
</script>
